var app = getApp();
import WeCropper from '../resource/we-cropper/we-cropper.js'
var dateTimePicker = require('../resource/js/dateTimePicker.js');

const device = wx.getSystemInfoSync();
const width = device.windowWidth;
const height = device.windowHeight-50;

Page(Object.assign({},{
    data:{
        options : null,
        inited : false,
        good : {},
        cropperOpt1: {
            id: 'cropper',
            width : width,
            height : height,
            scale: 2,
            zoom: 8,
            cut: {
                x: (width - 300) / 2,
                y: (height - 300) / 2,
                width: 300,
                height: 300
            }
        },
        cropperOpt2: {
            id: 'cropper',
            width : width,
            height : height,
            scale: 2,
            zoom: 8,
            cut: {
                x: (width - 300) / 2,
                y: (height - 180) / 2,
                width: 300,
                height: 180
            }
        },
		siteroot : app.siteInfo.siteroot.replace('app/index.php', ''),uniacid: app.siteInfo.uniacid,
    },
    onLoad:function(options){
        var self = this;
        self.setData({
            options : options,
        });
        var gid = options.gid ? options.gid : 0;
        app.com.auth(function(user){
            app.com.http('admin','POST',{op:'pubstart',gid:gid},0,false,'','',function(res){
                if (!res.data.errno) {
                    self.setData({
                        allsort : res.data.data.allsort,
                        allredbag : res.data.data.allredbag,
                        allshopsort : res.data.data.allshopsort,
                        good : res.data.data.good,
                        shop : res.data.data.shop,
                        shoplist : res.data.data.shoplist,
                        params : res.data.data.params,
                    },function(){
                        self.setData({
                            inited : true,
                            'good.address' : res.data.data.good.address ? res.data.data.good.address : res.data.data.shop.province + res.data.data.shop.city + res.data.data.shop.country+res.data.data.shop.street,
                            'good.tel' : res.data.data.good.tel ? res.data.data.good.tel : res.data.data.shop.tel,
                        });

                        var good = res.data.data.good;

                        var obj1 = dateTimePicker.dateTimePicker(2018,2030,good.start != 0 ? good.start : false);
                        var obj2 = dateTimePicker.dateTimePicker(2018,2030,good.end != 0 ? good.end : false);

                        obj1.dateTimeArray.pop();
                        obj1.dateTime.pop();
                        obj2.dateTimeArray.pop();
                        obj2.dateTime.pop();

                        self.setData({
                            'dateTimeArray.quickstart': obj1.dateTimeArray,
                            'dateTimeArray.quickend': obj2.dateTimeArray,
                            'dateTimeArray.groupstart': obj1.dateTimeArray,
                            'dateTimeArray.groupend': obj2.dateTimeArray,
                            'dateTimeArray.cutstart': obj1.dateTimeArray,
                            'dateTimeArray.cutend': obj2.dateTimeArray,
                            'dateTimeArray.actstart': obj1.dateTimeArray,
                            'dateTimeArray.actend': obj2.dateTimeArray,
                            'dateTimeArray.choustart': obj1.dateTimeArray,
                            'dateTimeArray.chouend': obj2.dateTimeArray,
                            'dateTimeArray.zcstart': obj1.dateTimeArray,
                            'dateTimeArray.zcend': obj2.dateTimeArray,

                            'dateTime.quickstart': obj1.dateTime,
                            'dateTime.quickend': obj2.dateTime,
                            'dateTime.groupstart': obj1.dateTime,
                            'dateTime.groupend': obj2.dateTime,
                            'dateTime.cutstart': obj1.dateTime,
                            'dateTime.cutend': obj2.dateTime,
                            'dateTime.actstart': obj1.dateTime,
                            'dateTime.actend': obj2.dateTime,
                            'dateTime.choustart': obj1.dateTime,
                            'dateTime.chouend': obj2.dateTime,
                            'dateTime.zcstart': obj1.dateTime,
                            'dateTime.zcend': obj2.dateTime,
                        });
                        
                    });
                    wx.setNavigationBarTitle({
                        title: '发布',
                    });

                }else{
                    app.com.alert( res.data.message,function(){
                        if( res.data.errno == 2 ){
                            app.globalData.adminurl = app.com.getUrlArgs();
                            wx.navigateTo({
                                url : res.data.data.url
                            });
                        }
                    });
                }
            });
        });
        
        self.crop1 = new WeCropper(self.data.cropperOpt1);
        self.crop2 = new WeCropper(self.data.cropperOpt2);

    },
    onPullDownRefresh: function () {
        var self = this;
        app.com.confirm('是否要重置数据?',function(){
            self.onLoad(self.data.options);
        });
        wx.stopPullDownRefresh();
    },
    addsever(){
        var self = this;
        if( !self.data.good.rule || self.data.good.rule.length <= 0 ){
            self.data.good.rule = [];
        }

        var id = new Date().getTime();
        self.data.good.rule.push( {id:id,name:'',price:''} );
        self.setData({
            'good.isrule' : 1,
            'good.rule' : self.data.good.rule,
        })
    },
    inputvalue(e){
        var self = this;
        var type = e.currentTarget.dataset.type;
        var value = e.detail.value;
        if( type == 'rule' ){
            var id = e.currentTarget.dataset.id;
            var name = e.currentTarget.dataset.typea;
            for (let i = 0,il = self.data.good.rule; i < il.length; i++) {
                if( il[i].id == id ){
                    var key =  'good.rule['+i+'].'+name;
                    self.setData({
                        [key] : value
                    })
                }
            }
        }else{
            self.setData({
                ['good.'+type] : value,
            })
        }
    },
    deleterule(e){
        var self = this;
        var id = e.currentTarget.dataset.id;
        for (let i = 0,il = self.data.good.rule; i < il.length; i++) {
            if( il[i].id == id ){
                self.data.good.rule.splice(i,1);
            }
        }
        var isrule = 1;
        if( self.data.good.rule.length <= 0 ) var isrule = 0;

        self.setData({
            'good.isrule' : isrule,
            'good.rule' : self.data.good.rule,
        })
    },
    radio(e){
        var self = this;
        var type = e.currentTarget.dataset.type;
        var value = e.currentTarget.dataset.v;

        if( type == 'shoplista' ){
            self.data.good.shoplista  = self.data.good.shoplista ? self.data.good.shoplista : [];

            var isin = -1;
            for (var i = 0; i < self.data.good.shoplista.length; i++) {
                if( self.data.good.shoplista[i] == value ){
                    isin = i;
                }
            }
            if( isin == -1 ){
                self.data.good.shoplista.push(value);
            }else{
                self.data.good.shoplista.splice(isin,1);
            }
            self.setData({
                'good.shoplista' : self.data.good.shoplista
            })

            for (var i = 0; i < self.data.shoplist.length; i++) {
                if( self.data.shoplist[i].id == value ){
                    self.setData({
                        ['shoplist['+i+'].checked'] : isin == -1 ? 1 : 0
                    })
                }
            }

        }else{
            var key =  'good.'+type;
            self.setData({
                [key] : value
            })
        }
    },
    uploadTap(e){
        var self = this;
        var type = e.currentTarget.dataset.type;
        self.setData({
            dealtype : type
        });
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success (res) {
                var  src = res.tempFilePaths[0];
                if( type == 'thumb' ) {
                    self.crop1.pushOrign(src);
                    self.setData({
                        showcanvas1 : true,
                    })
                }else if( type == 'thumbh' ){
                    self.crop2.pushOrign(src);
                    self.setData({
                        showcanvas2 : true,
                    })
                }
                app.com.alert( '请拖动到合适区域' );
            }
        })
    },
    getCropperImage(){
        var self = this;
        if( self.data.dealtype == 'thumb' ){

            self.crop1.getCropperImage((src) => {
                if (src) {
                    /*self.setData({
                        'good.thumbtemp' : src,
                    })*/

                    self.uptomaster(src,function(res){
                        self.setData({
                            'good.thumb' : res.attachment,
                            'good.showthumb' : res.url,
                            'good.thumbtemp' : '',
                        });
                    });

                } else {
                    app.com.alert( '裁剪失败' );
                }
                self.setData({
                    showcanvas1 : false,
                })
            })

        }else if( self.data.dealtype == 'thumbh' ){
            self.crop2.getCropperImage((src) => {
                if (src) {
                    self.uptomaster(src,function(res){
                        self.setData({
                            'good.thumbh' : res.attachment,
                            'good.showthumbh' : res.url,
                            'good.thumbhtemp' : '',
                        });
                    });
                } else {
                    app.com.alert( '裁剪失败' );
                }
                self.setData({
                    showcanvas2 : false,
                })
            })
        }
    },
    uploadMult(){
        var self = this;
        wx.chooseImage({
            count: 9, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success (res) {
                if( !self.data.good.pic || self.data.good.pic.length <= 0 ){
                    self.data.good.pic = [];
                }
                for(var t in res.tempFilePaths){
                    (function(m){
                        self.uptomaster(res.tempFilePaths[m],function(resa){
                            var temp = {id:m,att:resa.attachment,show:resa.url};
                            self.setData({
                                'good.pic' : self.data.good.pic.concat(temp)
                            });

                        });
                    })(t)
                }
            }
        })
    },
    pub(){
        var self = this;
        var good = self.data.good;

        if( !good.title ) {
            app.com.toast('请填入名称');return false;
        }
        if( !good.oldprice || good.oldprice*1 <= 0 ) {
            app.com.toast('请填入原价');return false;
        }        
        if( !good.thumb ) {
            app.com.toast('请上传封面图');return false;
        }
        if( !good.sortid ) {
            app.com.toast('请选择分类');return false;
        }
        self.savedata();
    },
    savedata(){
        var self = this;
        var form = JSON.stringify( self.data.good );
        app.com.http('admin','POST',{op:'pubgoods',form:form},0,true,'','',function(res){
            if (!res.data.errno) {
                app.com.alert(res.data.message,function(){
                    if( !self.data.good.id ){
                        self.setData({
                            good : {},
                        });
                    }
                });
            }else{
                app.com.toast( res.data.message );
                if( res.data.errno == 2 ){
                    wx.navigateTo({
                        url : res.data.data.url
                    });
                }
            }
        });
    },
    uptomaster(tempurl,fn){
        wx.showLoading({mask:true,title:'上传中'});
        wx.uploadFile({
            url: app.siteInfo.siteroot+'?i='+app.siteInfo.uniacid+'&j=&c=utility&a=file&do=upload&type=image&thumb=0',
            filePath: tempurl,
            name: 'file',
            success: function(res){
                var aaa = JSON.parse( res.data );
                if(aaa.attachment){
                    if( fn ) fn( aaa );
                }else{
                    app.com.alert( aaa.error ? aaa.error.message : '上传失败' );
                }
            },
            complete : function(){
                wx.hideLoading();
            }
        })
    },
    changesort(e){
        var type = e.detail.column;
        var value = e.detail.value;
        if( type == 0 ) {
            this.setData({
                'ssort[1]' : this.data.allsort[value].down
            })
        }
    },
    getsortvalue(e){
        var self = this;
        var value = e.detail.value;
        for (let i = 0,il = self.data.allsort; i < il.length; i++) {
            if( i == value ){
                self.setData({
                    'good.sortid' : il[i].id,
                    'good.sortname' : il[i].name,
                })
            }
        }
    },
    getshopsortvalue(e){
        var self = this;
        var value = e.detail.value;
        for (let i = 0,il = self.data.allshopsort; i < il.length; i++) {
            if( i == value ){
                self.setData({
                    'good.shopsort' : il[i].id,
                    'good.shopsortname' : il[i].name,
                })
            }
        }
    },
    getredbag(e){
        var self = this;
        var value = e.detail.value;
        for (let i = 0,il = self.data.allredbag; i < il.length; i++) {
            if( i == value ){
                var redname = il[i].name;
                if( il[i].id > 0 ){
                    redname = il[i].name+'('+this.data.params.dolper+ il[i].fee*100/100 +'，订单满'+ il[i].use*100/100 +'使用)';
                }
                self.setData({
                    'good.redid' : il[i].id,
                    'good.redname' : redname,
                })
            }
        }
    },
    deletepic(e){
        var self = this;
        var type = e.currentTarget.dataset.type;
        var id = e.currentTarget.dataset.id;
        app.com.confirm('确定删除此图片吗？',function(){
            if( type == 'temp' ){
                self.data.good.pictemp.splice(id,1);
                self.setData({
                    'good.pictemp' : self.data.good.pictemp,
                })
            }else if( type == 'pic' ){
                self.data.good.pic.splice(id,1);
                self.setData({
                    'good.pic' : self.data.good.pic,
                })
            }
        });
    },
    touchStart (e) {
        if( this.data.dealtype == 'thumb' ){
            this.crop1.touchStart(e)
        }else if( this.data.dealtype == 'thumbh' ){
            this.crop2.touchStart(e)
        }
    },
    touchMove (e) {
        if( this.data.dealtype == 'thumb' ){
            this.crop1.touchMove(e)
        }else if( this.data.dealtype == 'thumbh' ){
            this.crop2.touchMove(e)
        }
    },
    touchEnd (e) {
        if( this.data.dealtype == 'thumb' ){
            this.crop1.touchEnd(e)
        }else if( this.data.dealtype == 'thumbh' ){
            this.crop2.touchEnd(e)
        }
    },
    changeDateTimeColumn1(e) {
        var self = this;
        var type = e.currentTarget.dataset.type;
        var value = e.detail.value;
        self.setData({ 
            ['dateTime.'+type]: e.detail.value,
            ['good.'+type] : self.data.dateTimeArray[type][0][value[0]]+'-'+self.data.dateTimeArray[type][1][value[1]]+'-'+self.data.dateTimeArray[type][2][value[2]]+' '+self.data.dateTimeArray[type][3][value[3]]+':'+self.data.dateTimeArray[type][4][value[4]]
        });

    },
    toaddress(){
        wx.chooseAddress({
            success: function (res) {}
        })
    },
    location : function( e ){
        app.com.location( e );
    },
    otherapp : function( e ){
        app.com.otherapp( e );
    },
    navigateto : function( e ){
        app.com.navigateto( e );
    },
    redirectto : function( e ){
        app.com.redirectto( e );
    },    
    callphone : function(e){
        app.com.callphone( e );
    },
    
}))